<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>（Vue源码四）数据响应式原理 | Jeffery Blog</title><meta name="keywords" content="vue, 响应式原理，vue 源码"><meta name="author" content="志非"><meta name="copyright" content="志非"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="vue, vue 源码，Vue 源码目录及构建过程分析">
<meta property="og:type" content="article">
<meta property="og:title" content="（Vue源码四）数据响应式原理">
<meta property="og:url" content="https://fif.gitee.io/blog/2021/04/27/vue/vue-code-6.reactive/index.html">
<meta property="og:site_name" content="Jeffery Blog">
<meta property="og:description" content="vue, vue 源码，Vue 源码目录及构建过程分析">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/FIF/pic-beg/raw/master/images/vue/mvvm.png">
<meta property="article:published_time" content="2021-04-26T16:00:00.000Z">
<meta property="article:modified_time" content="2021-05-03T16:00:00.000Z">
<meta property="article:author" content="志非">
<meta property="article:tag" content="vue">
<meta property="article:tag" content="vue 源码">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/FIF/pic-beg/raw/master/images/vue/mvvm.png"><link rel="shortcut icon" href="/blog/img/home/avatar.jpeg"><link rel="canonical" href="https://fif.gitee.io/blog/2021/04/27/vue/vue-code-6.reactive/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: {"appId":"QYKLQ4BSGP","apiKey":"d45fc66694b4260b20711a30fdb5c4e1","indexName":"jeffery-blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":200,"position":"top","messagePrev":"本文修改于","messageNext":"天前，如果本文有一定的时效性，那么本文可能已经失效~"},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2021-05-04 00:00:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/blog/atom.xml" title="Jeffery Blog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><img class="load-image" src= "" data-lazy-src="/blog/img/loading.gif" alt=""/></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src= "" data-lazy-src="/blog/img/home/avatar.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">12</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/books/"><i class="fa-fw fas fa-book"></i><span> 阅读</span></a></li><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/blog/movies/"><i class="fa-fw fa fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/blog/gallery/"><i class="fa-fw far fa-image"></i><span> 相册</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/box/"><i class="fa-fw fab fa-xbox"></i><span> 聚宝盒</span></a></div><div class="menus_item"><a class="site-page" href="/blog/talk/"><i class="fa-fw far fa-comment"></i><span> 微语</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gitee.com/FIF/pic-beg/raw/master/images/vue/mvvm.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Jeffery Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fa fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 媒体</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/books/"><i class="fa-fw fas fa-book"></i><span> 阅读</span></a></li><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fa fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/blog/movies/"><i class="fa-fw fa fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/blog/gallery/"><i class="fa-fw far fa-image"></i><span> 相册</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/blog/box/"><i class="fa-fw fab fa-xbox"></i><span> 聚宝盒</span></a></div><div class="menus_item"><a class="site-page" href="/blog/talk/"><i class="fa-fw far fa-comment"></i><span> 微语</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fa fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">（Vue源码四）数据响应式原理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-04-26T16:00:00.000Z" title="发表于 2021-04-27 00:00:00">2021-04-27</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-05-03T16:00:00.000Z" title="更新于 2021-05-04 00:00:00">2021-05-04</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF/">前端</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF/vue/">vue</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%89%8D%E7%AB%AF/vue/vue-%E6%BA%90%E7%A0%81/">vue 源码</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">8.7k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>38分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="（Vue源码四）数据响应式原理"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="思考"><a href="#思考" class="headerlink" title="思考"></a>思考</h2><ul>
<li><code>Observer</code>，<code> Watcher</code>， <code>Dep</code> 3个类具体的作用、以及他们之间的关系。</li>
<li><code>props</code>,  <code>data</code>，<code>watch</code>，<code>computed</code> 响应式原理的实现？</li>
<li><code>Dep</code> 作为依赖管理的类，在什么时候进行实例化收集依赖？</li>
<li><code>Dep</code> 收集了什么类型的依赖？即 <code>watcher</code> 作为依赖的分类有哪些，分别是什么场景，以及区别在哪里？</li>
<li><code>Observer</code> 这个类具体对 <code>getter</code>, <code>setter</code> 方法做了哪些事情？</li>
<li>手写的 <code>watch</code> 和页面数据渲染监听的 <code>watch</code> 如果同时监听到数据的变化，优先级怎么排？</li>
<li>有了依赖的收集是不是还有依赖的解除，依赖解除的意义在哪里？</li>
</ul>
<p>带着这些问题，来分析 <code>Vue</code> 响应式实现原理</p>
<h2 id="响应式原理流程图分析"><a href="#响应式原理流程图分析" class="headerlink" title="响应式原理流程图分析"></a>响应式原理流程图分析</h2><p>先从全局了解整个响应式原理的流程，再从局部分析<code>props</code>、 <code>data</code>、<code>watcher</code>、<code>computed</code> 响应式的实现，由浅入深，逐渐深入</p>
<p><a data-fancybox target="_blank" rel="noopener" href="https://gitee.com/FIF/pic-beg/raw/master/images/vue/1620094396058-reactive-vue.png"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/1620094396058-reactive-vue.png" alt="组件化源码分析"></p>
</a>

<p>从上面流程图，我们可以了解到 <code>Observer</code>、<code>Watcher</code>、<code>Dep</code> 三者的作用已经关系：</p>
<ul>
<li><p><code>Observer</code> 类：实例化 <code>Observer</code> 类通过 <code>Object.defineProperty</code> 对数据的<code>getter</code>, <code>setter</code> 方法进行劫持改写，在 <code>getter</code> 阶段进行依赖的收集, 在数据发生更新阶段，触发 <code>setter</code> 进行依赖的更新</p>
</li>
<li><p><code>Watcher</code> 类：实例化 <code>watcher</code> 类相当于创建一个依赖，简单的理解是数据在哪里被使用就需要产生了一个依赖。当数据发生改变时，会通知到每个依赖进行更新</p>
</li>
</ul>
<ul>
<li><code>Dep</code> 类：<code>watcher</code> 理解为每个数据需要监听的依赖，对这些依赖的收集和通知则需要另一个类来管理，这个类便是 <code>Dep</code> , <code>Dep</code> 需要做的只有两件事，收集依赖和派发更新依赖。</li>
</ul>
<h2 id="vue-常用实例"><a href="#vue-常用实例" class="headerlink" title="vue 常用实例"></a>vue 常用实例</h2><p>通过一个常用的事例，分析 <code>props</code>,  <code>data</code>,  <code>watch</code> 和 <code>computed</code> 响应式，了解 <code>vue</code> 的响应式系统</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;app&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">p</span>&gt;</span>计数 &#123;&#123; num &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span><span class="tag">&lt;<span class="name">button</span> @<span class="attr">click</span>=<span class="string">&quot;change&quot;</span>&gt;</span>add<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">p</span>&gt;</span> &#123;&#123; computedNum &#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">    <span class="keyword">var</span> app = <span class="keyword">new</span> Vue(&#123;</span></span><br><span class="line">    data: &#123;</span><br><span class="line">      num: 0,</span><br><span class="line">    &#125;,</span><br><span class="line">    computed: &#123;</span><br><span class="line">      computedNum () &#123;</span><br><span class="line"><span class="javascript">        <span class="keyword">return</span> <span class="built_in">this</span>.num + <span class="number">2</span></span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    watch: &#123;</span><br><span class="line">      num (value) &#123;</span><br><span class="line"><span class="javascript">        <span class="built_in">console</span>.log(value)</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    methods: &#123;</span><br><span class="line">      change () &#123;</span><br><span class="line"><span class="javascript">        <span class="built_in">this</span>.num++</span></span><br><span class="line"><span class="javascript">        <span class="built_in">this</span>.computedNum++</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">    </span><br><span class="line">  &#125;)</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="初始化响应式"><a href="#初始化响应式" class="headerlink" title="初始化响应式"></a>初始化响应式</h2><p>从 实例化 <code>Vue</code> 开始, 实例化执行 <code>_init</code> 方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Vue</span> (<span class="params">options</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>._init(options)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>_init</code> 方法定义，它初始化我们的实例对象数据</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype._init = <span class="function"><span class="keyword">function</span> (<span class="params">options?: <span class="built_in">Object</span></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">    initState(vm)</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">    <span class="comment">// 有 el, 执行 $mount 方法</span></span><br><span class="line">    <span class="keyword">if</span> (vm.$options.el) &#123;</span><br><span class="line">      vm.$mount(vm.$options.el)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>

<p> <code>initState(vm)</code> 方法，它是构造响应式系统的核心，定义在 <code>src/core/instance/state.js</code> 中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initState</span> (<span class="params">vm</span>) </span>&#123;</span><br><span class="line">  vm._watchers = [];</span><br><span class="line">  <span class="keyword">var</span> opts = vm.$options;</span><br><span class="line">  <span class="comment">// 初始化 props</span></span><br><span class="line">  <span class="keyword">if</span> (opts.props) &#123; initProps(vm, opts.props); &#125;</span><br><span class="line">  <span class="comment">// 初始化 methods</span></span><br><span class="line">  <span class="keyword">if</span> (opts.methods) &#123; initMethods(vm, opts.methods); &#125;</span><br><span class="line">  <span class="comment">// 初始化 data</span></span><br><span class="line">  <span class="keyword">if</span> (opts.data) &#123;</span><br><span class="line">    initData(vm);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 如果没有定义data，则创建一个空对象，并设置为响应式</span></span><br><span class="line">    observe(vm._data = &#123;&#125;, <span class="literal">true</span> <span class="comment">/* asRootData */</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 初始化 computed</span></span><br><span class="line">  <span class="keyword">if</span> (opts.computed) &#123; initComputed(vm, opts.computed); &#125;</span><br><span class="line">  <span class="comment">// 初始化 watch</span></span><br><span class="line">  <span class="keyword">if</span> (opts.watch &amp;&amp; opts.watch !== nativeWatch) &#123;</span><br><span class="line">    initWatch(vm, opts.watch);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>initState</code> 方法主线很清晰，分别对 <code>props</code>、<code>methods</code>、<code>data</code>、<code>computed</code> 和 <code>wathcer</code> 定义的对象做了初始化操作，我们接下来依依分析。</p>
<h2 id="initProps-初始化props"><a href="#initProps-初始化props" class="headerlink" title="initProps - 初始化props"></a>initProps - 初始化props</h2><p>在初始化 <code>props</code> 之前，<code>vue</code> 已经做了两件事情，一是在选项合并的时候规范 <code>props</code>  ，二是接收父组件传递的值放在<code>propsData</code> 中。</p>
<p>最终调用 <code>defineReactive</code> 对 <code>props</code>的值做响应式处理</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initProps</span> (<span class="params">vm: Component, propsOptions: <span class="built_in">Object</span></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 接收父组件的值</span></span><br><span class="line">  <span class="keyword">const</span> propsData = vm.$options.propsData || &#123;&#125;</span><br><span class="line">  <span class="keyword">const</span> props = vm._props = &#123;&#125;</span><br><span class="line">  <span class="keyword">const</span> keys = vm.$options._propKeys = []</span><br><span class="line">  <span class="keyword">const</span> isRoot = !vm.$parent</span><br><span class="line">  <span class="comment">// 有父组件，props 嵌套对象不做响应式处理</span></span><br><span class="line">  <span class="keyword">if</span> (!isRoot) &#123;</span><br><span class="line">    toggleObserving(<span class="literal">false</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 遍历 props</span></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> propsOptions) &#123;</span><br><span class="line">    keys.push(key)</span><br><span class="line">    <span class="comment">// 校验 props 属性 ，并取得 props 属性值</span></span><br><span class="line">    <span class="keyword">const</span> value = validateProp(key, propsOptions, propsData, vm)</span><br><span class="line">    <span class="comment">// 对 props 进行赋值，会执行回调报错</span></span><br><span class="line">    defineReactive(props, key, value, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (!isRoot &amp;&amp; !isUpdatingChildComponent) &#123;</span><br><span class="line">        warn(</span><br><span class="line">          <span class="string">`Avoid mutating a prop directly since the value will be `</span> +</span><br><span class="line">          <span class="string">`overwritten whenever the parent component re-renders. `</span> +</span><br><span class="line">          <span class="string">`Instead, use a data or computed property based on the prop&#x27;s `</span> +</span><br><span class="line">          <span class="string">`value. Prop being mutated: &quot;<span class="subst">$&#123;key&#125;</span>&quot;`</span>,</span><br><span class="line">          vm</span><br><span class="line">        )</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">if</span> (!(key <span class="keyword">in</span> vm)) &#123;</span><br><span class="line">      proxy(vm, <span class="string">`_props`</span>, key)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  toggleObserving(<span class="literal">true</span>)</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>初始化 <code>props</code> 流程</p>
<ul>
<li><p>如果是子组件，执行<code>toggleObserving(false)</code> ，<code>props</code> 的嵌套对象不会进行响应式处理，因为父组件传递对象的时候已经实现了响应式</p>
</li>
<li><p>遍历定义的 <code>props</code> 对象，执行 <code>validateProp</code> 方法检验 <code>props</code> 属性并取得它的值，</p>
</li>
<li><p> <code>defineReactive</code> 方法把每个 <code>prop</code> 对应的值变成响应式；如果 <code>props</code> 赋值触发 <code>setter</code> 方法，执行第四个参数的回调函数控制台报错，这也是我们常说的单向数据流</p>
</li>
<li><p>通过 <code>proxy</code> 把 <code>vm._props.xxx</code> 的访问代理到 <code>vm.xxx</code> 上。</p>
</li>
</ul>
<h2 id="initMethods-初始化-methods"><a href="#initMethods-初始化-methods" class="headerlink" title="initMethods - 初始化 methods"></a>initMethods - 初始化 methods</h2><p><code>initMethod</code>方法和介绍的响应式没有任何的关系，他的实现也相对简单，主要是保证 <code>methods</code>  方法定义必须是函数，且命名不能和<code>props</code> 以及 <code>vm</code> 实例属性方法重复，最终会将定义的方法都挂载到实例上。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initMethods</span> (<span class="params">vm, methods</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> props = vm.$options.props;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> methods) &#123;</span><br><span class="line">      &#123;</span><br><span class="line">        <span class="comment">// method必须为函数形式</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">typeof</span> methods[key] !== <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">          warn(</span><br><span class="line">            <span class="string">&quot;Method \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; has type \&quot;&quot;</span> + (<span class="keyword">typeof</span> methods[key]) + <span class="string">&quot;\&quot; in the component definition. &quot;</span> +</span><br><span class="line">            <span class="string">&quot;Did you reference the function correctly?&quot;</span>,</span><br><span class="line">            vm</span><br><span class="line">          );</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// methods方法名不能和props重复</span></span><br><span class="line">        <span class="keyword">if</span> (props &amp;&amp; hasOwn(props, key)) &#123;</span><br><span class="line">          warn(</span><br><span class="line">            (<span class="string">&quot;Method \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; has already been defined as a prop.&quot;</span>),</span><br><span class="line">            vm</span><br><span class="line">          );</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//  不能以_ or $.这些Vue保留标志开头</span></span><br><span class="line">        <span class="keyword">if</span> ((key <span class="keyword">in</span> vm) &amp;&amp; isReserved(key)) &#123;</span><br><span class="line">          warn(</span><br><span class="line">            <span class="string">&quot;Method \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; conflicts with an existing Vue instance method. &quot;</span> +</span><br><span class="line">            <span class="string">&quot;Avoid defining component methods that start with _ or $.&quot;</span></span><br><span class="line">          );</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 直接挂载到实例的属性上,可以通过vm[method]访问。</span></span><br><span class="line">      vm[key] = <span class="keyword">typeof</span> methods[key] !== <span class="string">&#x27;function&#x27;</span> ? noop : bind(methods[key], vm);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>



<h2 id="initData-初始化-data"><a href="#initData-初始化-data" class="headerlink" title="initData - 初始化 data"></a>initData - 初始化 data</h2><p><code>initData</code> 遍历 <code>data</code> 对象，保证它的属性不能和 <code>props，methods</code> 重复，接着调用<code>proxy</code> 代理属性到 <code>vm</code> 实例上，最后调用 <code>observe</code> 实现 <code>data</code> 响应式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initData</span>(<span class="params">vm</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> data = vm.$options.data;</span><br><span class="line">  <span class="comment">// 根实例时，data是一个对象，子组件的data是一个函数，其中getData会调用函数返回data对象</span></span><br><span class="line">  data = vm._data = <span class="keyword">typeof</span> data === <span class="string">&#x27;function&#x27;</span>? getData(data, vm): data || &#123;&#125;;</span><br><span class="line">  <span class="keyword">var</span> keys = <span class="built_in">Object</span>.keys(data);</span><br><span class="line">  <span class="keyword">var</span> props = vm.$options.props;</span><br><span class="line">  <span class="keyword">var</span> methods = vm.$options.methods;</span><br><span class="line">  <span class="keyword">var</span> i = keys.length;</span><br><span class="line">  <span class="keyword">while</span> (i--) &#123;</span><br><span class="line">    <span class="keyword">var</span> key = keys[i];</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="comment">// 命名不能和方法重复</span></span><br><span class="line">      <span class="keyword">if</span> (methods &amp;&amp; hasOwn(methods, key)) &#123;</span><br><span class="line">        warn((<span class="string">&quot;Method \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; has already been defined as a data property.&quot;</span>),vm);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 命名不能和props重复</span></span><br><span class="line">    <span class="keyword">if</span> (props &amp;&amp; hasOwn(props, key)) &#123;</span><br><span class="line">      warn(<span class="string">&quot;The data property \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; is already declared as a prop. &quot;</span> + <span class="string">&quot;Use prop default value instead.&quot;</span>,vm);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!isReserved(key)) &#123;</span><br><span class="line">      <span class="comment">// 数据代理，用户可直接通过vm实例返回data数据</span></span><br><span class="line">      proxy(vm, <span class="string">&quot;_data&quot;</span>, key);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// observe data</span></span><br><span class="line">  observe(data, <span class="literal">true</span> <span class="comment">/* asRootData */</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="data-依赖收集"><a href="#data-依赖收集" class="headerlink" title="data 依赖收集"></a>data 依赖收集</h3><p><code>observe</code> 执行会实例化一个 <code>Observer</code>类，这个类的定义如下(忽略数组类型的<code>data</code>):</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// initData </span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initData</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">  observe(data, <span class="literal">true</span>)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// observe</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">observe</span>(<span class="params">value, asRootData</span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">  ob = <span class="keyword">new</span> Observer(value);</span><br><span class="line">  <span class="keyword">return</span> ob</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>Observer</code> 观察者类，定义对象或数组getter和setter方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Observer = <span class="function"><span class="keyword">function</span> <span class="title">Observer</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value</span><br><span class="line">    <span class="built_in">this</span>.dep = <span class="keyword">new</span> Dep() <span class="comment">// 依赖收集</span></span><br><span class="line">    <span class="comment">// 将__ob__属性设置成不可枚举属性。外部无法通过遍历获取。</span></span><br><span class="line">    def(value, <span class="string">&#x27;__ob__&#x27;</span>, <span class="built_in">this</span>);</span><br><span class="line">    <span class="comment">// 数组处理</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(value)) &#123;</span><br><span class="line">        ···</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// 对象处理</span></span><br><span class="line">      <span class="built_in">this</span>.walk(value);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">def</span> (<span class="params">obj, key, val, enumerable</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(obj, key, &#123;</span><br><span class="line">    value: val,</span><br><span class="line">    enumerable: !!enumerable, <span class="comment">// 是否可枚举</span></span><br><span class="line">    writable: <span class="literal">true</span>,</span><br><span class="line">    configurable: <span class="literal">true</span></span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>Observer</code>会为<code>data</code>添加一个<code>__ob__</code>属性， <code>__ob__</code>属性是作为响应式对象的标志，<code>data</code> 是一个对象调用<code>walk</code>方法，遍历对象上每个属性执行 <code>defineReactive</code>, 它进行<code>getter,setter</code>的改写。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Observer.prototype.walk = <span class="function"><span class="keyword">function</span> <span class="title">walk</span> (<span class="params">obj</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 获取对象所有属性，遍历调用defineReactive###1进行改写</span></span><br><span class="line">    <span class="keyword">var</span> keys = <span class="built_in">Object</span>.keys(obj);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; keys.length; i++) &#123;</span><br><span class="line">        defineReactive(obj, keys[i]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>



<p> <code>defineReactive </code>是响应式构建的核心，它会先<strong>实例化一个<code>Dep</code>类，即为每个数据都创建一个依赖的管理</strong>，之后利用 <code>Object.defineProperty</code> 重写 <code>getter,setter</code> 方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineReactive</span> (<span class="params">obj,key,val,customSetter,shallow</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 每个数据实例化一个Dep类，创建一个依赖的管理</span></span><br><span class="line">    <span class="keyword">var</span> dep = <span class="keyword">new</span> Dep();</span><br><span class="line">    <span class="keyword">var</span> property = <span class="built_in">Object</span>.getOwnPropertyDescriptor(obj, key);</span><br><span class="line">    <span class="comment">// 属性必须满足可配置</span></span><br><span class="line">    <span class="keyword">if</span> (property &amp;&amp; property.configurable === <span class="literal">false</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// cater for pre-defined getter/setters</span></span><br><span class="line">    <span class="keyword">var</span> getter = property &amp;&amp; property.get;</span><br><span class="line">    <span class="keyword">var</span> setter = property &amp;&amp; property.set;</span><br><span class="line">    <span class="comment">// 这一部分的逻辑是针对深层次的对象，如果对象的属性是一个对象，则会递归调用实例化Observe类，让其属性值也转换为响应式对象</span></span><br><span class="line">    <span class="keyword">var</span> childOb = !shallow &amp;&amp; observe(val);</span><br><span class="line">    <span class="built_in">Object</span>.defineProperty(obj, key, &#123;</span><br><span class="line">      enumerable: <span class="literal">true</span>,</span><br><span class="line">      configurable: <span class="literal">true</span>,s</span><br><span class="line">      get: <span class="function"><span class="keyword">function</span> <span class="title">reactiveGetter</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> value = getter ? getter.call(obj) : val;</span><br><span class="line">        <span class="keyword">if</span> (Dep.target) &#123;</span><br><span class="line">          <span class="comment">// 为当前watcher添加dep数据</span></span><br><span class="line">          dep.depend();</span><br><span class="line">          <span class="keyword">if</span> (childOb) &#123;</span><br><span class="line">            childOb.dep.depend();</span><br><span class="line">            <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(value)) &#123;</span><br><span class="line">              dependArray(value);</span><br><span class="line">            &#125;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> value</span><br><span class="line">      &#125;,</span><br><span class="line">      set: <span class="function"><span class="keyword">function</span> <span class="title">reactiveSetter</span> (<span class="params">newVal</span>) </span>&#123;&#125;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>



<h3 id="dep-实例化"><a href="#dep-实例化" class="headerlink" title="dep 实例化"></a>dep 实例化</h3><p>从上面分析，我们得知 <code>Dep</code> 实例化有两处：</p>
<ul>
<li><p><code>defineReactive</code> 方法<code>new Dep</code></p>
</li>
<li><p>在实例化 <code>Observer</code> 执行构造器，<code>new Dep</code></p>
</li>
</ul>
<p>其实 <code>Vue</code> 这样设计是有依据的，第一处实例化 <code>Dep</code> 是为了访问对象属性时进行收集依赖。第二处实例化是为了数组响应式处理，数据响应式重写了数组的7个方法，调用数组方法更新，需要拿到数组 <code>dep</code> 实例进行派发更新，只有挂载在数组值身上才能拿到。但不管是数组还是对象，最终都是在 <code>getter</code> 方法进行依赖收集</p>
<h3 id="data-派发更新"><a href="#data-派发更新" class="headerlink" title="data 派发更新"></a>data 派发更新</h3><p>在数据发生改变时，会执行定义好的<code>setter</code>方法，我们先看源码。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Object</span>.defineProperty(obj,key, &#123;</span><br><span class="line">  ···</span><br><span class="line">  set: <span class="function"><span class="keyword">function</span> <span class="title">reactiveSetter</span> (<span class="params">newVal</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">var</span> value = getter ? getter.call(obj) : val;</span><br><span class="line">      <span class="comment">// 新值和旧值相等时，跳出操作</span></span><br><span class="line">      <span class="keyword">if</span> (newVal === value || (newVal !== newVal &amp;&amp; value !== value)) &#123;</span><br><span class="line">        <span class="keyword">return</span></span><br><span class="line">      &#125;</span><br><span class="line">      ···</span><br><span class="line">      <span class="comment">// 新值为对象时，会为新对象进行依赖收集过程</span></span><br><span class="line">      childOb = !shallow &amp;&amp; observe(newVal);</span><br><span class="line">      dep.notify();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>



<p>派发更新阶段会做以下几件事：</p>
<ul>
<li>判断数据更改前后是否一致，如果数据相等则不进行任何派发更新操作。</li>
<li>赋值 <code>newVal</code>，调用 <code>observe</code>，对新值做响应式处理。</li>
<li>调用该数据依赖收集器的<code>dep.notify</code>方法进行派发更新。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Dep.prototype.notify = <span class="function"><span class="keyword">function</span> <span class="title">notify</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> subs = <span class="built_in">this</span>.subs.slice();</span><br><span class="line">  <span class="keyword">if</span> (!config.async) &#123;</span><br><span class="line">    <span class="comment">// 根据依赖的id进行排序</span></span><br><span class="line">    subs.sort(<span class="function"><span class="keyword">function</span> (<span class="params">a, b</span>) </span>&#123; <span class="keyword">return</span> a.id - b.id; &#125;);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = subs.length; i &lt; l; i++) &#123;</span><br><span class="line">    <span class="comment">// 遍历每个依赖，进行更新数据操作。</span></span><br><span class="line">    subs[i].update();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>



<p><code>update</code> 更新时会将<code>watcher</code>推到队列中，等待下一个<code>nextTick</code>到来时可以拿到更新的依赖 <code>watcher</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Watcher.prototype.update = <span class="function"><span class="keyword">function</span> <span class="title">update</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">  queueWatcher(<span class="built_in">this</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>



<p><code>queueWatcher</code>方法的调用，会将数据所收集的依赖依次推到<code>queue</code>数组中,数组会在下一个事件循环<code>nextTick</code>执行</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">queueWatcher</span> (<span class="params">watcher</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> id = watcher.id;</span><br><span class="line">  <span class="comment">// 保证同一个watcher只执行一次</span></span><br><span class="line">  <span class="keyword">if</span> (has[id] == <span class="literal">null</span>) &#123;</span><br><span class="line">    has[id] = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">if</span> (!flushing) &#123;</span><br><span class="line">      queue.push(watcher);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">var</span> i = queue.length - <span class="number">1</span>;</span><br><span class="line">      <span class="keyword">while</span> (i &gt; index &amp;&amp; queue[i].id &gt; watcher.id) &#123;</span><br><span class="line">        i--;</span><br><span class="line">      &#125;</span><br><span class="line">      queue.splice(i + <span class="number">1</span>, <span class="number">0</span>, watcher);</span><br><span class="line">    &#125;</span><br><span class="line">    ···</span><br><span class="line">    nextTick(flushSchedulerQueue);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>当下一个<code>nextTick</code>到来时，会执行<code>flushSchedulerQueue</code>方法，它会拿到收集的<code>queue</code>数组(这是一个<code>watcher</code>的集合),并对数组依赖进行排序。为什么进行排序呢？源码中解释了三点：</p>
<blockquote>
<p>组件创建是先父后子，所以组件的更新也是先父后子，因此需要保证父的渲染<code>watcher</code>优先于子的渲染<code>watcher</code>更新。</p>
<p><strong>用户自定义的<code>watcher</code>,称为<code>user watcher</code>。 <code>user watcher</code>和<code>render watcher</code>执行也有先后，由于<code>user watchers</code>比<code>render watcher</code>要先创建，所以<code>user watcher</code>要优先执行</strong>。</p>
<p>如果一个组件在父组件的 <code>watcher</code> 执行阶段被销毁，那么它对应的 <code>watcher</code> 执行都可以被跳过。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">flushSchedulerQueue</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    currentFlushTimestamp = getNow();</span><br><span class="line">    flushing = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">var</span> watcher, id;</span><br><span class="line">    <span class="comment">// 对queue的watcher进行排序</span></span><br><span class="line">    queue.sort(<span class="function"><span class="keyword">function</span> (<span class="params">a, b</span>) </span>&#123; <span class="keyword">return</span> a.id - b.id; &#125;);</span><br><span class="line">    <span class="comment">// 循环执行queue.length，为了确保由于渲染时添加新的依赖导致queue的长度不断改变。</span></span><br><span class="line">    <span class="keyword">for</span> (index = <span class="number">0</span>; index &lt; queue.length; index++) &#123;</span><br><span class="line">      watcher = queue[index];</span><br><span class="line">      <span class="comment">// 如果watcher定义了before的配置，则优先执行before方法</span></span><br><span class="line">      <span class="keyword">if</span> (watcher.before) &#123;</span><br><span class="line">        watcher.before();</span><br><span class="line">      &#125;</span><br><span class="line">      id = watcher.id;</span><br><span class="line">      has[id] = <span class="literal">null</span>;</span><br><span class="line">      watcher.run();</span><br><span class="line">      <span class="comment">//...</span></span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>



<p><code>flushSchedulerQueue</code>阶段，重要的过程可以总结为四点：</p>
<blockquote>
<p>对<code>queue</code>中的<code>watcher</code>进行排序，原因上面已经总结。</p>
<p>遍历<code>watcher</code>,如果当前<code>watcher</code>有<code>before</code>配置，则执行<code>before</code>方法，对应前面的渲染<code>watcher</code>:在渲染<code>watcher</code>实例化时，我们传递了<code>before</code>函数，即在下个<code>tick</code>更新视图前，会调用<code>beforeUpdate</code>生命周期钩子。</p>
<p>执行<code>watcher.run</code>进行修改的操作。</p>
<p>重置恢复状态，这个阶段会将一些流程控制的状态变量恢复为初始值，并清空记录<code>watcher</code>的队列。</p>
</blockquote>
<p><code>beforeUpdate</code> 定义</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Watcher(vm, updateComponent, noop, &#123;</span><br><span class="line">  before: <span class="function"><span class="keyword">function</span> <span class="title">before</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (vm._isMounted &amp;&amp; !vm._isDestroyed) &#123;</span><br><span class="line">      callHook(vm, <span class="string">&#x27;beforeUpdate&#x27;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;, <span class="literal">true</span> <span class="comment">/* isRenderWatcher */</span>);</span><br></pre></td></tr></table></figure>



<p>重点看看<code>watcher.run()</code>的操作。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">Watcher.prototype.run = <span class="function"><span class="keyword">function</span> <span class="title">run</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">this</span>.active) &#123;</span><br><span class="line">      <span class="keyword">var</span> value = <span class="built_in">this</span>.get();</span><br><span class="line">      <span class="keyword">if</span> ( value !== <span class="built_in">this</span>.value || isObject(value) || <span class="built_in">this</span>.deep ) &#123;</span><br><span class="line">        <span class="comment">// 设置新值</span></span><br><span class="line">        <span class="keyword">var</span> oldValue = <span class="built_in">this</span>.value;</span><br><span class="line">        <span class="built_in">this</span>.value = value;</span><br><span class="line">        <span class="comment">// 针对user watcher，暂时不分析</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">this</span>.user) &#123;</span><br><span class="line">          <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="built_in">this</span>.cb.call(<span class="built_in">this</span>.vm, value, oldValue);</span><br><span class="line">          &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">            handleError(e, <span class="built_in">this</span>.vm, (<span class="string">&quot;callback for watcher \&quot;&quot;</span> + (<span class="built_in">this</span>.expression) + <span class="string">&quot;\&quot;&quot;</span>));</span><br><span class="line">          &#125;</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="built_in">this</span>.cb.call(<span class="built_in">this</span>.vm, value, oldValue);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>



<p>首先会执行<code>watcher.prototype.get</code>的方法，得到数据变化后的当前值，之后会对新值做判断，如果判断满足条件，则执行<code>cb</code>，<code>cb</code>为实例化<code>watcher</code>时传入的回调。</p>
<p>在分析<code>get</code>方法前，回头看看<code>watcher</code>构造函数的几个属性定义</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> watcher = <span class="function"><span class="keyword">function</span> <span class="title">Watcher</span>(<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  vm, <span class="comment">// 组件实例</span></span></span></span><br><span class="line"><span class="function"><span class="params">  expOrFn, <span class="comment">// 执行函数</span></span></span></span><br><span class="line"><span class="function"><span class="params">  cb, <span class="comment">// 回调</span></span></span></span><br><span class="line"><span class="function"><span class="params">  options, <span class="comment">// 配置</span></span></span></span><br><span class="line"><span class="function"><span class="params">  isRenderWatcher <span class="comment">// 是否为渲染watcher</span></span></span></span><br><span class="line"><span class="function"><span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.vm = vm;</span><br><span class="line">    <span class="keyword">if</span> (isRenderWatcher) &#123;</span><br><span class="line">      vm._watcher = <span class="built_in">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    vm._watchers.push(<span class="built_in">this</span>);</span><br><span class="line">    <span class="comment">// options</span></span><br><span class="line">    <span class="keyword">if</span> (options) &#123;</span><br><span class="line">      <span class="built_in">this</span>.deep = !!options.deep;</span><br><span class="line">      <span class="built_in">this</span>.user = !!options.user;</span><br><span class="line">      <span class="built_in">this</span>.lazy = !!options.lazy;</span><br><span class="line">      <span class="built_in">this</span>.sync = !!options.sync;</span><br><span class="line">      <span class="built_in">this</span>.before = options.before;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.deep = <span class="built_in">this</span>.user = <span class="built_in">this</span>.lazy = <span class="built_in">this</span>.sync = <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">this</span>.cb = cb;</span><br><span class="line">    <span class="built_in">this</span>.id = ++uid$<span class="number">2</span>; <span class="comment">// uid for batching</span></span><br><span class="line">    <span class="built_in">this</span>.active = <span class="literal">true</span>;</span><br><span class="line">    <span class="built_in">this</span>.dirty = <span class="built_in">this</span>.lazy; <span class="comment">// for lazy watchers</span></span><br><span class="line">    <span class="built_in">this</span>.deps = [];</span><br><span class="line">    <span class="built_in">this</span>.newDeps = [];</span><br><span class="line">    <span class="built_in">this</span>.depIds = <span class="keyword">new</span> _Set();</span><br><span class="line">    <span class="built_in">this</span>.newDepIds = <span class="keyword">new</span> _Set();</span><br><span class="line">    <span class="built_in">this</span>.expression = expOrFn.toString();</span><br><span class="line">    <span class="comment">// parse expression for getter</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> expOrFn === <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">      <span class="built_in">this</span>.getter = expOrFn;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.getter = parsePath(expOrFn);</span><br><span class="line">      <span class="keyword">if</span> (!<span class="built_in">this</span>.getter) &#123;</span><br><span class="line">        <span class="built_in">this</span>.getter = noop;</span><br><span class="line">        warn(</span><br><span class="line">          <span class="string">&quot;Failed watching path: \&quot;&quot;</span> + expOrFn + <span class="string">&quot;\&quot; &quot;</span> +</span><br><span class="line">          <span class="string">&#x27;Watcher only accepts simple dot-delimited paths. &#x27;</span> +</span><br><span class="line">          <span class="string">&#x27;For full control, use a function instead.&#x27;</span>,</span><br><span class="line">          vm</span><br><span class="line">        );</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// lazy为计算属性标志，当watcher为计算watcher时，不会理解执行get方法进行求值</span></span><br><span class="line">    <span class="built_in">this</span>.value = <span class="built_in">this</span>.lazy</span><br><span class="line">      ? <span class="literal">undefined</span></span><br><span class="line">      : <span class="built_in">this</span>.get();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>方法<code>get</code>的定义如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Watcher.prototype.get = <span class="function"><span class="keyword">function</span> <span class="title">get</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    pushTarget(<span class="built_in">this</span>);</span><br><span class="line">    <span class="keyword">var</span> value;</span><br><span class="line">    <span class="keyword">var</span> vm = <span class="built_in">this</span>.vm;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      value = <span class="built_in">this</span>.getter.call(vm, vm);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">     ···</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">      ···</span><br><span class="line">      <span class="comment">// 把Dep.target恢复到上一个状态，依赖收集过程完成</span></span><br><span class="line">      popTarget();</span><br><span class="line">      <span class="built_in">this</span>.cleanupDeps();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> value</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p><code>get</code>方法会执行<code>this.getter</code>进行求值，在当前渲染<code>watcher</code>的条件下,<code>getter</code>会执行视图更新的操作。这一阶段会<strong>重新渲染页面组件</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> Watcher(vm, updateComponent, noop, &#123; <span class="attr">before</span>: <span class="function">() =&gt;</span> &#123;&#125; &#125;, <span class="literal">true</span>);</span><br><span class="line">updateComponent = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  vm._update(vm._render(), hydrating);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>



<h3 id="依赖清除"><a href="#依赖清除" class="headerlink" title="依赖清除"></a>依赖清除</h3><p>执行完<code>getter</code>方法后，最后一步会进行依赖的清除，也就是<code>cleanupDeps</code>的过程。</p>
<blockquote>
<p>关于依赖清除的作用，我们列举一个场景： 我们经常会使用<code>v-if</code>来进行模板的切换，切换过程中会执行不同的模板渲染，如果A模板监听a数据，B模板监听b数据，当渲染模板B时，如果不进行旧依赖的清除，在B模板的场景下，a数据的变化同样会引起依赖的重新渲染更新，这会造成性能的浪费。因此旧依赖的清除在优化阶段是有必要。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 依赖清除的过程</span></span><br><span class="line">  Watcher.prototype.cleanupDeps = <span class="function"><span class="keyword">function</span> <span class="title">cleanupDeps</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> i = <span class="built_in">this</span>.deps.length;</span><br><span class="line">    <span class="keyword">while</span> (i--) &#123;</span><br><span class="line">      <span class="keyword">var</span> dep = <span class="built_in">this</span>.deps[i];</span><br><span class="line">      <span class="keyword">if</span> (!<span class="built_in">this</span>.newDepIds.has(dep.id)) &#123;</span><br><span class="line">        dep.removeSub(<span class="built_in">this</span>);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">var</span> tmp = <span class="built_in">this</span>.depIds;</span><br><span class="line">    <span class="built_in">this</span>.depIds = <span class="built_in">this</span>.newDepIds;</span><br><span class="line">    <span class="built_in">this</span>.newDepIds = tmp;</span><br><span class="line">    <span class="built_in">this</span>.newDepIds.clear();</span><br><span class="line">    tmp = <span class="built_in">this</span>.deps;</span><br><span class="line">    <span class="built_in">this</span>.deps = <span class="built_in">this</span>.newDeps;</span><br><span class="line">    <span class="built_in">this</span>.newDeps = tmp;</span><br><span class="line">    <span class="built_in">this</span>.newDeps.length = <span class="number">0</span>;</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>



<p>总结成依赖派发更新的最后两个点</p>
<ul>
<li><strong>执行<code>run</code>操作会执行<code>getter</code>方法,也就是重新计算新值，针对渲染<code>watcher</code>而言，会重新执行<code>updateComponent</code>进行视图更新</strong></li>
<li><strong>重新计算<code>getter</code>后，会进行依赖的清除</strong></li>
</ul>
<h2 id="initComputed-初始化-compouted"><a href="#initComputed-初始化-compouted" class="headerlink" title="initComputed - 初始化 compouted"></a>initComputed - 初始化 compouted</h2><p><code>initComputed</code> 是 <code>computed</code> 数据的初始化, 源码实现逻辑：</p>
<ul>
<li><p><code>computed</code> 可以是对象，也可以是函数，但是对象必须有 <code>getter</code> 方法, 如果 <code>computed</code> 中的属性值是对象时需要进行验证。</p>
</li>
<li><p>针对 <code>computed</code> 的每个属性，要创建一个监听的依赖，也就是实例化一个 <code>watcher</code>， <code>watcher</code>的定义，可以暂时理解为数据使用的依赖本身，一个 <code>watcher</code> 实例代表了一个需要被监听的数据依赖。</p>
</li>
<li><p><code>initComputed</code>  将每个 <code>computed</code> 属性设置成响应式的数据，同样的，也会对<code>computed</code>的命名做检测，防止与 <code>props,data</code> 冲突。</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// computed watcher的标志，lazy属性为true</span></span><br><span class="line"><span class="keyword">var</span> computedWatcherOptions = &#123; <span class="attr">lazy</span>: <span class="literal">true</span> &#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initComputed</span> (<span class="params">vm, computed</span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> computed) &#123;</span><br><span class="line">      <span class="keyword">var</span> userDef = computed[key];</span><br><span class="line">      <span class="keyword">var</span> getter = <span class="keyword">typeof</span> userDef === <span class="string">&#x27;function&#x27;</span> ? userDef : userDef.get;</span><br><span class="line">      <span class="comment">// computed属性为对象时，要保证有getter方法</span></span><br><span class="line">      <span class="keyword">if</span> (getter == <span class="literal">null</span>) &#123;</span><br><span class="line">        warn((<span class="string">&quot;Getter is missing for computed property \&quot;&quot;</span> + key + <span class="string">&quot;\&quot;.&quot;</span>),vm);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (!isSSR) &#123;</span><br><span class="line">        <span class="comment">// 创建computed watcher</span></span><br><span class="line">        watchers[key] = <span class="keyword">new</span> Watcher(vm,getter || noop,noop,computedWatcherOptions);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (!(key <span class="keyword">in</span> vm)) &#123;</span><br><span class="line">        <span class="comment">// 设置为响应式数据</span></span><br><span class="line">        defineComputed(vm, key, userDef);</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 不能和props，data命名冲突</span></span><br><span class="line">        <span class="keyword">if</span> (key <span class="keyword">in</span> vm.$data) &#123;</span><br><span class="line">          warn((<span class="string">&quot;The computed property \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; is already defined in data.&quot;</span>), vm);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (vm.$options.props &amp;&amp; key <span class="keyword">in</span> vm.$options.props) &#123;</span><br><span class="line">          warn((<span class="string">&quot;The computed property \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; is already defined as a prop.&quot;</span>), vm);</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>defineComputed</code>的逻辑和分析<code>data</code>的逻辑相似，最终调用 <code>Object.defineProperty</code> 进行数据拦截。具体的定义如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineComputed</span> (<span class="params">target,key,userDef</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 非服务端渲染会对getter进行缓存</span></span><br><span class="line">  <span class="keyword">var</span> shouldCache = !isServerRendering();</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> userDef === <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">    <span class="comment">// </span></span><br><span class="line">    sharedPropertyDefinition.get = shouldCache</span><br><span class="line">      ? createComputedGetter(key)</span><br><span class="line">      : createGetterInvoker(userDef);</span><br><span class="line">    sharedPropertyDefinition.set = noop;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    sharedPropertyDefinition.get = userDef.get</span><br><span class="line">      ? shouldCache &amp;&amp; userDef.cache !== <span class="literal">false</span></span><br><span class="line">        ? createComputedGetter(key)</span><br><span class="line">        : createGetterInvoker(userDef.get)</span><br><span class="line">      : noop;</span><br><span class="line">    sharedPropertyDefinition.set = userDef.set || noop;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (sharedPropertyDefinition.set === noop) &#123;</span><br><span class="line">    sharedPropertyDefinition.set = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">      warn(</span><br><span class="line">        (<span class="string">&quot;Computed property \&quot;&quot;</span> + key + <span class="string">&quot;\&quot; was assigned to but it has no setter.&quot;</span>),</span><br><span class="line">        <span class="built_in">this</span></span><br><span class="line">      );</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(target, key, sharedPropertyDefinition);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>在非服务端渲染的情形，计算属性的计算结果会被缓存，缓存的意义在于，<strong>只有在相关响应式数据发生变化时，<code>computed</code>才会重新求值，其余情况多次访问计算属性的值都会返回之前计算的结果，这就是缓存的优化</strong></p>
<p><code>computed</code>属性有两种写法，一种是函数，另一种是对象，其中对象的写法需要提供 <code>getter</code> 和 <code>setter</code> 方法。</p>
<p>当访问到 <code>computed</code> 属性时，会触发 <code>getter</code> 方法进行依赖收集，看看<code>createComputedGetter</code>的实现。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createComputedGetter</span> (<span class="params">key</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">computedGetter</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> watcher = <span class="built_in">this</span>._computedWatchers &amp;&amp; <span class="built_in">this</span>._computedWatchers[key]</span><br><span class="line">    <span class="keyword">if</span> (watcher) &#123;</span><br><span class="line">      <span class="comment">// dirty是标志是否已经执行过计算结果，如果执行过则不会执行watcher.evaluate重复计算，这也是缓存的原理</span></span><br><span class="line">      <span class="keyword">if</span> (watcher.dirty) &#123;</span><br><span class="line">        watcher.evaluate()</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (Dep.target) &#123;</span><br><span class="line">        watcher.depend()</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> watcher.value</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>createComputedGetter</code>返回的函数在执行过程中会先拿到属性的<code>computed watcher</code>, <code>dirty</code> 标志是否已经执行过计算结果，如果执行过则不会执行<code>watcher.evaluate</code>重复计算，这也是缓存的原理。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">Watcher.prototype.evaluate = <span class="function"><span class="keyword">function</span> <span class="title">evaluate</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 对于计算属性而言 evaluate的作用是执行计算回调</span></span><br><span class="line">    <span class="built_in">this</span>.value = <span class="built_in">this</span>.get();</span><br><span class="line">    <span class="built_in">this</span>.dirty = <span class="literal">false</span>;</span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>



<h3 id="computed-依赖收集"><a href="#computed-依赖收集" class="headerlink" title="computed 依赖收集"></a>computed 依赖收集</h3><p>和 <code>data</code> 分析一样，当访问 <code>computed</code> 属性会触发 <code>computedGetter</code> 方法，<code>watcher.dirty</code> 为 <code>true</code> 执行 <code>watcher.evaluate()</code> 从而调用 <code>get</code> 方法，如果 computed 计算访问 <code>data</code> 数据的属性值，会触发 <code>data</code> 数据的<code>getter</code>方法进行依赖收集，根据前面分析，<code>data</code>的<code>Dep</code>收集器会将当前 <code>watcher</code> 作为依赖进行收集，而这个<code>watcher</code>就是 <code>computed watcher</code>，并且会为当前的 <code>watcher</code> 添加访问的数据<code>Dep</code></p>
<p>回到计算执行函数的<code>this.get()</code>方法，<code>getter</code>执行完成后同样会进行依赖的清除，原理和目的参考<code>data</code>阶段的分析。<code>get</code>执行完毕后会进入<code>watcher.depend</code>进行依赖的收集。收集过程和<code>data</code>一致,将当前的<code>computed watcher</code>作为依赖收集到数据的依赖收集器<code>Dep</code>中。</p>
<p>这就是<code>computed</code>依赖收集的完整过程，对比<code>data</code>的依赖收集，<code>computed</code>会对运算的结果进行缓存，避免重复执行运算过程。</p>
<h3 id="computed-派发更新"><a href="#computed-派发更新" class="headerlink" title="computed 派发更新"></a>computed 派发更新</h3><ul>
<li>当计算属性依赖的数据发生更新时，由于数据的<code>Dep</code>收集过<code>computed watch</code>这个依赖，所以会调用<code>dep</code>的<code>notify</code>方法，对依赖进行状态更新。</li>
<li>此时<code>computed watcher</code>和之前介绍的<code>watcher</code>不同，它不会立刻执行依赖的更新操作，而是通过一个<code>dirty</code>进行标记。我们再回头看<code>依赖更新</code>的代码。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">Dep.prototype.notify = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">   <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = subs.length; i &lt; l; i++) &#123;</span><br><span class="line">      subs[i].update();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">Watcher.prototype.update = <span class="function"><span class="keyword">function</span> <span class="title">update</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 计算属性分支  </span></span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">this</span>.lazy) &#123;</span><br><span class="line">    <span class="built_in">this</span>.dirty = <span class="literal">true</span>;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="built_in">this</span>.sync) &#123;</span><br><span class="line">    <span class="built_in">this</span>.run();</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    queueWatcher(<span class="built_in">this</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>



<p>由于<code>lazy</code>属性的存在，<code>update</code>过程不会执行状态更新的操作，只会将<code>dirty</code>标记为<code>true</code>。</p>
<ul>
<li>由于 <code>data</code> 数据拥有渲染 <code>watcher</code> 这个依赖，所以同时会执行<code>updateComponent</code>进行视图重新渲染,而<code>render</code>过程中会访问到计算属性,此时由于<code>this.dirty</code>值为<code>true</code>,又会对计算属性重新求值。</li>
</ul>
<h2 id="initWatch-初始化-watch"><a href="#initWatch-初始化-watch" class="headerlink" title="initWatch - 初始化 watch"></a>initWatch - 初始化 watch</h2><p>初始化 <code>watch</code> ，遍历 <code>watch</code>, 如果 watch 属性值是一个数组，则递归处理。<code>initWatch</code>的核心是<code>createWatcher</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initWatch</span> (<span class="params">vm: Component, watch: <span class="built_in">Object</span></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> watch) &#123;</span><br><span class="line">    <span class="keyword">const</span> handler = watch[key]</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(handler)) &#123;</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; handler.length; i++) &#123;</span><br><span class="line">        createWatcher(vm, key, handler[i])</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      createWatcher(vm, key, handler)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createWatcher</span> (<span class="params">vm,expOrFn,handler,options</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 针对watch是对象的形式，此时回调回选项中的handler</span></span><br><span class="line">    <span class="keyword">if</span> (isPlainObject(handler)) &#123;</span><br><span class="line">      options = handler;</span><br><span class="line">      handler = handler.handler;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> handler === <span class="string">&#x27;string&#x27;</span>) &#123;</span><br><span class="line">      handler = vm[handler];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> vm.$watch(expOrFn, handler, options)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>



<h3 id="watch-依赖收集"><a href="#watch-依赖收集" class="headerlink" title="watch 依赖收集"></a>watch 依赖收集</h3><p>无论是选项的形式，还是<code>api</code>的形式，最终都会调用实例的<code>$watch</code>方法，其中<code>expOrFn</code>是监听的字符串，<code>handler</code>是监听的回调函数，<code>options</code>是相关配置。我们重点看看<code>$watch</code>的实现</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">Vue.prototype.$watch = <span class="function"><span class="keyword">function</span> (<span class="params">expOrFn,cb,options</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> vm = <span class="built_in">this</span>;</span><br><span class="line">    <span class="keyword">if</span> (isPlainObject(cb)) &#123;</span><br><span class="line">      <span class="keyword">return</span> createWatcher(vm, expOrFn, cb, options)</span><br><span class="line">    &#125;</span><br><span class="line">    options = options || &#123;&#125;;</span><br><span class="line">    options.user = <span class="literal">true</span>;</span><br><span class="line">    <span class="keyword">var</span> watcher = <span class="keyword">new</span> Watcher(vm, expOrFn, cb, options);</span><br><span class="line">    <span class="comment">// 当watch有immediate选项时，立即执行cb方法，即不需要等待属性变化，立刻执行回调。</span></span><br><span class="line">    <span class="keyword">if</span> (options.immediate) &#123;</span><br><span class="line">      <span class="keyword">try</span> &#123;</span><br><span class="line">        cb.call(vm, watcher.value);</span><br><span class="line">      &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">        handleError(error, vm, (<span class="string">&quot;callback for immediate watcher \&quot;&quot;</span> + (watcher.expression) + <span class="string">&quot;\&quot;&quot;</span>));</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">unwatchFn</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">      watcher.teardown();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><code>$watch</code>的核心是创建一个<code>user watcher</code>, <code>user</code>是当前用户定义<code>watcher</code>的标志。如果有<code>immediate</code>属性，则立即执行回调函数。而实例化<code>watcher</code>时会执行一次<code>getter</code>求值，这时，<code>user watcher</code>会作为依赖被数据所收集。这个过程可以参考<code>data</code>的分析。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> Watcher = <span class="function"><span class="keyword">function</span> <span class="title">Watcher</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> expOrFn === <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">      <span class="built_in">this</span>.getter = expOrFn</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.getter = parsePath(expOrFn)</span><br><span class="line">      <span class="keyword">if</span> (!<span class="built_in">this</span>.getter) &#123;</span><br><span class="line">        <span class="built_in">this</span>.getter = noop</span><br><span class="line">        process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span> &amp;&amp; warn(</span><br><span class="line">          <span class="string">`Failed watching path: &quot;<span class="subst">$&#123;expOrFn&#125;</span>&quot; `</span> +</span><br><span class="line">          <span class="string">&#x27;Watcher only accepts simple dot-delimited paths. &#x27;</span> +</span><br><span class="line">          <span class="string">&#x27;For full control, use a function instead.&#x27;</span>,</span><br><span class="line">          vm</span><br><span class="line">        )</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  <span class="built_in">this</span>.value = <span class="built_in">this</span>.lazy</span><br><span class="line">      ? <span class="literal">undefined</span></span><br><span class="line">      : <span class="built_in">this</span>.get();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 解析字符串</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parsePath</span> (<span class="params">path: string</span>): <span class="title">any</span> </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (bailRE.test(path)) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> segments = path.split(<span class="string">&#x27;.&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">obj</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; segments.length; i++) &#123;</span><br><span class="line">      <span class="keyword">if</span> (!obj) <span class="keyword">return</span></span><br><span class="line">      obj = obj[segments[i]]</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> obj</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Watcher.prototype.get = <span class="function"><span class="keyword">function</span> <span class="title">get</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  ···</span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="comment">// getter回调函数，触发依赖收集</span></span><br><span class="line">    value = <span class="built_in">this</span>.getter.call(vm, vm);</span><br><span class="line">  &#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="watch-派发更新"><a href="#watch-派发更新" class="headerlink" title="watch 派发更新"></a>watch 派发更新</h3><p><code>watch</code> 派发更新，当数据发生改变时，<code>setter</code>拦截对依赖进行更新，而此前<code>user watcher</code>已经被当成依赖收集了。这个时候依赖的更新就是回调函数的执行。</p>
<h2 id="Watcher"><a href="#Watcher" class="headerlink" title="Watcher"></a>Watcher</h2><p>从上面分析，我们知道在初始化 <code>computed</code> 和 <code>watch</code> 都会实例化 <code>Watcher</code> 类，实际上 <code>watcher</code> 实例化总共分为三类，分别是 <code>render watcher</code>, <code>user watcher</code>, <code>computed watcher</code>, 它们对应的场景是渲染时要收集的依赖，用户定义的 <code>watch</code>, 以及用户定义的 <code>computed</code>。通过<code>isRenderWatcher</code>, <code>user</code>, <code>lazy</code> 区分</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> watcher = <span class="function"><span class="keyword">function</span> <span class="title">Watcher</span>(<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  vm, <span class="comment">// 组件实例</span></span></span></span><br><span class="line"><span class="function"><span class="params">  expOrFn, <span class="comment">// 执行函数</span></span></span></span><br><span class="line"><span class="function"><span class="params">  cb, <span class="comment">// 回调</span></span></span></span><br><span class="line"><span class="function"><span class="params">  options, <span class="comment">// 配置</span></span></span></span><br><span class="line"><span class="function"><span class="params">  isRenderWatcher <span class="comment">// 是否为渲染watcher</span></span></span></span><br><span class="line"><span class="function"><span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">this</span>.vm = vm;</span><br><span class="line">    <span class="keyword">if</span> (isRenderWatcher) &#123; <span class="comment">// 渲染</span></span><br><span class="line">      vm._watcher = <span class="built_in">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    vm._watchers.push(<span class="built_in">this</span>);</span><br><span class="line">    <span class="comment">// options</span></span><br><span class="line">    <span class="keyword">if</span> (options) &#123;</span><br><span class="line">      <span class="built_in">this</span>.user = !!options.user; <span class="comment">// watch 用户定义</span></span><br><span class="line">      <span class="built_in">this</span>.lazy = !!options.lazy; <span class="comment">// computed 定义</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.deep = <span class="built_in">this</span>.user = <span class="built_in">this</span>.lazy = <span class="built_in">this</span>.sync = <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">this</span>.cb = cb;</span><br><span class="line">    <span class="built_in">this</span>.dirty = <span class="built_in">this</span>.lazy; <span class="comment">// for lazy watchers</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="响应式-API"><a href="#响应式-API" class="headerlink" title="响应式 API"></a>响应式 API</h2><h3 id="set"><a href="#set" class="headerlink" title="set"></a>set</h3><p><code>set</code> 方法给对象或数组添加一个 <code>响应式值</code>, 它是弥补 <code>Object.defineProperty</code> 无法监控到对象新增的值，以下是它的实现原理：</p>
<ul>
<li>目标对象必须为非空的对象，可以是数组，否则抛出异常。</li>
<li>如果目标对象是数组时，调用数组的 <code>splice</code> 方法，遇到数组新增元素的场景，会调用 <code>ob.observeArray(inserted)</code> 对数组新增的元素收集依赖。</li>
<li>新增的属性值在原对象中已经存在，则手动访问新的属性值，这一过程会触发依赖收集。</li>
<li>如果目标对象不是响应式对象，直接返回。如果是响应式对象，调用<code>defineReactive</code> 方法手动定义新属性的 <code>getter,setter</code> 方法，并通过 <code>notify</code> 触发依赖更新。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">set</span> (<span class="params">target: <span class="built_in">Array</span>&lt;any&gt; | <span class="built_in">Object</span>, key: any, val: any</span>): <span class="title">any</span> </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span> &amp;&amp;</span><br><span class="line">    (isUndef(target) || isPrimitive(target))</span><br><span class="line">  ) &#123;</span><br><span class="line">    warn(<span class="string">`Cannot set reactive property on undefined, null, or primitive value: <span class="subst">$&#123;(target: any)&#125;</span>`</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 数组场景，调用重写的splice方法，对新添加属性收集依赖。</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(target) &amp;&amp; isValidArrayIndex(key)) &#123;</span><br><span class="line">    target.length = <span class="built_in">Math</span>.max(target.length, key)</span><br><span class="line">    target.splice(key, <span class="number">1</span>, val)</span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 新增对象的属性存在时，直接返回新属性，触发依赖收集</span></span><br><span class="line">  <span class="keyword">if</span> (key <span class="keyword">in</span> target &amp;&amp; !(key <span class="keyword">in</span> <span class="built_in">Object</span>.prototype)) &#123;</span><br><span class="line">    target[key] = val</span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> ob = (target: any).__ob__</span><br><span class="line">  <span class="comment">// 数据是组件实例，直接返回</span></span><br><span class="line">  <span class="keyword">if</span> (target._isVue || (ob &amp;&amp; ob.vmCount)) &#123;</span><br><span class="line">    process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span> &amp;&amp; warn(</span><br><span class="line">      <span class="string">&#x27;Avoid adding reactive properties to a Vue instance or its root $data &#x27;</span> +</span><br><span class="line">      <span class="string">&#x27;at runtime - declare it upfront in the data option.&#x27;</span></span><br><span class="line">    )</span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line">  &#125;</span><br><span class="line">   <span class="comment">// 目标源对象本身不是一个响应式对象，则不需要处理</span></span><br><span class="line">  <span class="keyword">if</span> (!ob) &#123;</span><br><span class="line">    target[key] = val</span><br><span class="line">    <span class="keyword">return</span> val</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 手动调用defineReactive，为新属性设置getter,setter</span></span><br><span class="line">  defineReactive(ob.value, key, val)</span><br><span class="line">  <span class="comment">// 修改响应式数据派发更新</span></span><br><span class="line">  ob.dep.notify()</span><br><span class="line">  <span class="keyword">return</span> val</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="del"><a href="#del" class="headerlink" title="del"></a>del</h3><p><code>del</code> 方法使用场景比较少，它是删除对象的属性，然后派发更新。以下是它的实现原理。</p>
<ul>
<li><p>如果目标对象是数组时，调用数组的 <code>splice</code> 方法删除。</p>
</li>
<li><p>目标对象不存在属性，直接返回，否则使用 <code>delete</code> 删除属性</p>
</li>
<li><p>如果是响应式对象，派发更新</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">del</span> (<span class="params">target: <span class="built_in">Array</span>&lt;any&gt; | <span class="built_in">Object</span>, key: any</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span> &amp;&amp;</span><br><span class="line">    (isUndef(target) || isPrimitive(target))</span><br><span class="line">  ) &#123;</span><br><span class="line">    warn(<span class="string">`Cannot delete reactive property on undefined, null, or primitive value: <span class="subst">$&#123;(target: any)&#125;</span>`</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(target) &amp;&amp; isValidArrayIndex(key)) &#123;</span><br><span class="line">    target.splice(key, <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">const</span> ob = (target: any).__ob__</span><br><span class="line">  <span class="keyword">if</span> (target._isVue || (ob &amp;&amp; ob.vmCount)) &#123;</span><br><span class="line">    process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span> &amp;&amp; warn(</span><br><span class="line">      <span class="string">&#x27;Avoid deleting properties on a Vue instance or its root $data &#x27;</span> +</span><br><span class="line">      <span class="string">&#x27;- just set it to null.&#x27;</span></span><br><span class="line">    )</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (!hasOwn(target, key)) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">delete</span> target[key]</span><br><span class="line">  <span class="keyword">if</span> (!ob) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 修改响应式数据派发更新</span></span><br><span class="line">  ob.dep.notify()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="响应式过程"><a href="#响应式过程" class="headerlink" title="响应式过程"></a>响应式过程</h2><p><a data-fancybox target="_blank" rel="noopener" href="http://assets.processon.com/chart_image/6039bd87f346fb1149000367.png"><img src= "" data-lazy-src="http://assets.processon.com/chart_image/6039bd87f346fb1149000367.png" alt="挂载流程图"></a></p>
<h2 id="手动实现一个响应式"><a href="#手动实现一个响应式" class="headerlink" title="手动实现一个响应式"></a>手动实现一个响应式</h2><p>以下是手动实现一个响应式的简约版</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br><span class="line">267</span><br><span class="line">268</span><br><span class="line">269</span><br><span class="line">270</span><br><span class="line">271</span><br><span class="line">272</span><br><span class="line">273</span><br><span class="line">274</span><br><span class="line">275</span><br><span class="line">276</span><br><span class="line">277</span><br><span class="line">278</span><br><span class="line">279</span><br><span class="line">280</span><br><span class="line">281</span><br><span class="line">282</span><br><span class="line">283</span><br><span class="line">284</span><br><span class="line">285</span><br><span class="line">286</span><br><span class="line">287</span><br><span class="line">288</span><br><span class="line">289</span><br><span class="line">290</span><br><span class="line">291</span><br><span class="line">292</span><br><span class="line">293</span><br><span class="line">294</span><br><span class="line">295</span><br><span class="line">296</span><br><span class="line">297</span><br><span class="line">298</span><br><span class="line">299</span><br><span class="line">300</span><br><span class="line">301</span><br><span class="line">302</span><br><span class="line">303</span><br><span class="line">304</span><br><span class="line">305</span><br><span class="line">306</span><br><span class="line">307</span><br><span class="line">308</span><br><span class="line">309</span><br><span class="line">310</span><br><span class="line">311</span><br><span class="line">312</span><br><span class="line">313</span><br><span class="line">314</span><br><span class="line">315</span><br><span class="line">316</span><br><span class="line">317</span><br><span class="line">318</span><br><span class="line">319</span><br><span class="line">320</span><br><span class="line">321</span><br><span class="line">322</span><br><span class="line">323</span><br><span class="line">324</span><br><span class="line">325</span><br><span class="line">326</span><br><span class="line">327</span><br><span class="line">328</span><br><span class="line">329</span><br><span class="line">330</span><br><span class="line">331</span><br><span class="line">332</span><br><span class="line">333</span><br><span class="line">334</span><br><span class="line">335</span><br><span class="line">336</span><br><span class="line">337</span><br><span class="line">338</span><br><span class="line">339</span><br><span class="line">340</span><br><span class="line">341</span><br><span class="line">342</span><br><span class="line">343</span><br><span class="line">344</span><br><span class="line">345</span><br><span class="line">346</span><br><span class="line">347</span><br><span class="line">348</span><br><span class="line">349</span><br><span class="line">350</span><br><span class="line">351</span><br><span class="line">352</span><br><span class="line">353</span><br><span class="line">354</span><br><span class="line">355</span><br><span class="line">356</span><br><span class="line">357</span><br><span class="line">358</span><br><span class="line">359</span><br><span class="line">360</span><br><span class="line">361</span><br><span class="line">362</span><br><span class="line">363</span><br><span class="line">364</span><br><span class="line">365</span><br><span class="line">366</span><br><span class="line">367</span><br><span class="line">368</span><br><span class="line">369</span><br><span class="line">370</span><br><span class="line">371</span><br><span class="line">372</span><br><span class="line">373</span><br><span class="line">374</span><br><span class="line">375</span><br><span class="line">376</span><br><span class="line">377</span><br><span class="line">378</span><br><span class="line">379</span><br><span class="line">380</span><br><span class="line">381</span><br><span class="line">382</span><br><span class="line">383</span><br><span class="line">384</span><br><span class="line">385</span><br><span class="line">386</span><br><span class="line">387</span><br><span class="line">388</span><br><span class="line">389</span><br><span class="line">390</span><br><span class="line">391</span><br><span class="line">392</span><br><span class="line">393</span><br><span class="line">394</span><br><span class="line">395</span><br><span class="line">396</span><br><span class="line">397</span><br><span class="line">398</span><br><span class="line">399</span><br><span class="line">400</span><br><span class="line">401</span><br><span class="line">402</span><br><span class="line">403</span><br><span class="line">404</span><br><span class="line">405</span><br><span class="line">406</span><br><span class="line">407</span><br><span class="line">408</span><br><span class="line">409</span><br><span class="line">410</span><br><span class="line">411</span><br><span class="line">412</span><br><span class="line">413</span><br><span class="line">414</span><br><span class="line">415</span><br><span class="line">416</span><br><span class="line">417</span><br><span class="line">418</span><br><span class="line">419</span><br><span class="line">420</span><br><span class="line">421</span><br><span class="line">422</span><br><span class="line">423</span><br><span class="line">424</span><br><span class="line">425</span><br><span class="line">426</span><br><span class="line">427</span><br><span class="line">428</span><br><span class="line">429</span><br><span class="line">430</span><br><span class="line">431</span><br><span class="line">432</span><br><span class="line">433</span><br><span class="line">434</span><br><span class="line">435</span><br><span class="line">436</span><br><span class="line">437</span><br><span class="line">438</span><br><span class="line">439</span><br><span class="line">440</span><br><span class="line">441</span><br><span class="line">442</span><br><span class="line">443</span><br><span class="line">444</span><br><span class="line">445</span><br><span class="line">446</span><br><span class="line">447</span><br><span class="line">448</span><br><span class="line">449</span><br><span class="line">450</span><br><span class="line">451</span><br><span class="line">452</span><br><span class="line">453</span><br><span class="line">454</span><br><span class="line">455</span><br><span class="line">456</span><br><span class="line">457</span><br><span class="line">458</span><br><span class="line">459</span><br><span class="line">460</span><br><span class="line">461</span><br><span class="line">462</span><br><span class="line">463</span><br><span class="line">464</span><br><span class="line">465</span><br><span class="line">466</span><br><span class="line">467</span><br><span class="line">468</span><br><span class="line">469</span><br><span class="line">470</span><br><span class="line">471</span><br><span class="line">472</span><br><span class="line">473</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">noop</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"><span class="keyword">const</span> sharedPropertyDefinition = &#123;</span><br><span class="line">  enumerable: <span class="literal">true</span>,</span><br><span class="line">  configurable: <span class="literal">true</span>,</span><br><span class="line">  get: noop,</span><br><span class="line">  set: noop</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">proxy</span> (<span class="params">target, sourceKey, key</span>) </span>&#123;</span><br><span class="line">  sharedPropertyDefinition.get = <span class="function"><span class="keyword">function</span> <span class="title">proxyGetter</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>[sourceKey][key]</span><br><span class="line">  &#125;</span><br><span class="line">  sharedPropertyDefinition.set = <span class="function"><span class="keyword">function</span> <span class="title">proxySetter</span> (<span class="params">val</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>[sourceKey][key] = val</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(target, key, sharedPropertyDefinition)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> defaultTagRE = <span class="regexp">/\&#123;\&#123;(\w+?)\&#125;\&#125;/g</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parseText</span> (<span class="params">vm, html</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> tagRE = defaultTagRE</span><br><span class="line">  <span class="keyword">if</span> (!tagRE.test(html)) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">let</span> match</span><br><span class="line">  <span class="keyword">while</span> ((match = tagRE.exec(html))) &#123;</span><br><span class="line">    html = html.replace(match[<span class="number">0</span>], vm[match[<span class="number">1</span>]])</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> html</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Vue</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">options</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>._init(options)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  _init (options) &#123;</span><br><span class="line">    <span class="keyword">const</span> vm = <span class="built_in">this</span></span><br><span class="line">    <span class="built_in">this</span>.$options = options;</span><br><span class="line">    <span class="built_in">this</span>.initState(vm)</span><br><span class="line">    <span class="comment">// 有 el, 执行 $mount 方法</span></span><br><span class="line">    <span class="keyword">if</span> (vm.$options.el) &#123;</span><br><span class="line">      vm.$mount(vm.$options.el)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">initState</span>(<span class="params">vm</span>)</span> &#123;</span><br><span class="line">    vm._watchers = []</span><br><span class="line">    <span class="keyword">const</span> opts = vm.$options</span><br><span class="line">    <span class="comment">// 调用 observe 方法设置 data 为响应式，并且避免和 props、methods 重名</span></span><br><span class="line">    <span class="keyword">if</span> (opts.data) &#123;</span><br><span class="line">      initData(vm)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      observe(vm._data = &#123;&#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 初始化 computed</span></span><br><span class="line">    <span class="keyword">if</span> (opts.computed) &#123;</span><br><span class="line">      initComputed(vm, opts.computed)</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 初始化 watch</span></span><br><span class="line">    <span class="keyword">if</span> (opts.watch) &#123;</span><br><span class="line">      initWatch(vm, opts.watch)</span><br><span class="line">    &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 对外暴露调用订阅者的接口，内部主要在指令中使用订阅者</span></span><br><span class="line">    $watch(expOrFn, cb, options) &#123;</span><br><span class="line">      <span class="keyword">const</span> watcher = <span class="keyword">new</span> Watcher(<span class="built_in">this</span>, expOrFn, cb, &#123;<span class="attr">user</span>: <span class="literal">true</span>&#125;);</span><br><span class="line">      <span class="comment">// 立即执行</span></span><br><span class="line">      <span class="keyword">if</span> (options.immediate) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">          cb.call(<span class="built_in">this</span>, watcher.val)</span><br><span class="line">        &#125; <span class="keyword">catch</span> (error) &#123;</span><br><span class="line">          <span class="built_in">console</span>.error(<span class="string">`callback for immediate watcher &quot;<span class="subst">$&#123;watcher.expression&#125;</span>&quot;`</span>)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      </span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    $mount(el) &#123;</span><br><span class="line">      <span class="comment">// 直接改写innerHTML</span></span><br><span class="line">      <span class="keyword">const</span> vm = <span class="built_in">this</span></span><br><span class="line">      <span class="keyword">let</span> innerHtml = el &amp;&amp; <span class="built_in">document</span>.querySelector(el)</span><br><span class="line">      </span><br><span class="line">      <span class="keyword">const</span> updateComponent = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (innerHtml) &#123;</span><br><span class="line">          <span class="keyword">let</span> template = <span class="string">&#x27;&#x27;</span></span><br><span class="line">          <span class="keyword">if</span> (<span class="built_in">this</span>.$options.template) &#123;</span><br><span class="line">            template = <span class="built_in">this</span>.$options.template</span><br><span class="line">          &#125;</span><br><span class="line">          innerHtml = compileText(<span class="built_in">this</span>, template)</span><br><span class="line">          </span><br><span class="line">          <span class="built_in">document</span>.querySelector(el).innerHTML = innerHtml</span><br><span class="line"></span><br><span class="line">          <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">document</span>.querySelector(<span class="string">&#x27;#change&#x27;</span>).addEventListener(<span class="string">&#x27;click&#x27;</span>, <span class="function">() =&gt;</span> &#123;</span><br><span class="line">              <span class="built_in">console</span>.log(<span class="string">&#x27;333&#x27;</span>)</span><br><span class="line">              vm.age = vm.age + <span class="number">1</span></span><br><span class="line">            &#125;)</span><br><span class="line">          &#125;, <span class="number">0</span>)</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 创建一个渲染的依赖。</span></span><br><span class="line">      <span class="keyword">new</span> Watcher(<span class="built_in">this</span>, updateComponent, noop, &#123;</span><br><span class="line">        before () &#123;</span><br><span class="line">          <span class="comment">// beforeUpdate 钩子函数</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;, <span class="literal">true</span>)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">compileText</span> (<span class="params">vm, html</span>) </span>&#123;</span><br><span class="line">    html = parseText(vm, html)</span><br><span class="line">    <span class="keyword">return</span> html</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 初始化 data</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">vm</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initData</span>(<span class="params">vm</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> data = vm.$options.data</span><br><span class="line">  <span class="comment">// 定义私有属性 _data, 根实例时，data是一个对象，子组件的data是一个函数</span></span><br><span class="line">  data = vm._data = <span class="keyword">typeof</span> data === <span class="string">&#x27;function&#x27;</span></span><br><span class="line">    ? data.call(vm, vm)</span><br><span class="line">    : data || &#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> keys = <span class="built_in">Object</span>.keys(data)</span><br><span class="line">  <span class="keyword">let</span> i = keys.length</span><br><span class="line">  <span class="keyword">while</span> (i--) &#123;</span><br><span class="line">    <span class="keyword">const</span> key = keys[i]</span><br><span class="line">    proxy(vm, <span class="string">`_data`</span>, key)</span><br><span class="line">  &#125;</span><br><span class="line">  observe(data)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> computedWatcherOptions = &#123; <span class="attr">lazy</span>: <span class="literal">true</span> &#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initComputed</span>(<span class="params">vm, computed</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> watchers = vm._computedWatchers = <span class="built_in">Object</span>.create(<span class="literal">null</span>)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> computed) &#123;</span><br><span class="line">    <span class="keyword">const</span> userDef = computed[key]</span><br><span class="line">    <span class="keyword">const</span> getter = <span class="keyword">typeof</span> userDef === <span class="string">&#x27;function&#x27;</span> ? userDef : userDef.get</span><br><span class="line">    <span class="comment">// 要保证有getter方法</span></span><br><span class="line">    <span class="keyword">if</span> (getter == <span class="literal">null</span>) &#123;</span><br><span class="line">      <span class="built_in">console</span>.error(</span><br><span class="line">        <span class="string">`Getter is missing for computed property &quot;<span class="subst">$&#123;key&#125;</span>&quot;.`</span></span><br><span class="line">      )</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    watchers[key] = <span class="keyword">new</span> Watcher(</span><br><span class="line">      vm,</span><br><span class="line">      getter || noop,</span><br><span class="line">      noop,</span><br><span class="line">      computedWatcherOptions</span><br><span class="line">    )</span><br><span class="line"></span><br><span class="line">    <span class="comment">// component-defined computed properties are already defined on the</span></span><br><span class="line">    <span class="comment">// component prototype. We only need to define computed properties defined</span></span><br><span class="line">    <span class="comment">// at instantiation here.</span></span><br><span class="line">    <span class="keyword">if</span> (!(key <span class="keyword">in</span> vm)) &#123;</span><br><span class="line">      <span class="comment">// 设置为响应式数据</span></span><br><span class="line">      defineComputed(vm, key, userDef)</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (process.env.NODE_ENV !== <span class="string">&#x27;production&#x27;</span>) &#123;</span><br><span class="line">      <span class="comment">// 不能和props，data命名冲突</span></span><br><span class="line">      <span class="keyword">if</span> (key <span class="keyword">in</span> vm.$data) &#123;</span><br><span class="line">        <span class="built_in">console</span>.error(<span class="string">`The computed property &quot;<span class="subst">$&#123;key&#125;</span>&quot; is already defined in data.`</span>)</span><br><span class="line">      &#125; <span class="keyword">else</span> <span class="keyword">if</span> (vm.$options.props &amp;&amp; key <span class="keyword">in</span> vm.$options.props) &#123;</span><br><span class="line">        <span class="built_in">console</span>.error(<span class="string">`The computed property &quot;<span class="subst">$&#123;key&#125;</span>&quot; is already defined as a prop.`</span>)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineComputed</span> (<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  target,</span></span></span><br><span class="line"><span class="function"><span class="params">  key,</span></span></span><br><span class="line"><span class="function"><span class="params">  <span class="comment">// userDef</span></span></span></span><br><span class="line"><span class="function"><span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">  sharedPropertyDefinition.get = createComputedGetter(key)</span><br><span class="line">  sharedPropertyDefinition.set = noop</span><br><span class="line">  </span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(target, key, sharedPropertyDefinition)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createComputedGetter</span> (<span class="params">key</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">computedGetter</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> watcher = <span class="built_in">this</span>._computedWatchers &amp;&amp; <span class="built_in">this</span>._computedWatchers[key]</span><br><span class="line">    <span class="keyword">if</span> (watcher) &#123;</span><br><span class="line">      <span class="comment">// dirty是标志是否已经执行过计算结果，如果执行过则不会执行watcher.evaluate重复计算，这也是缓存的原理</span></span><br><span class="line">      <span class="keyword">if</span> (watcher.dirty) &#123;</span><br><span class="line">        watcher.evaluate()</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">// 将 computed watch 收集到当前 watch 实例下所有的 deps</span></span><br><span class="line">      <span class="keyword">if</span> (Dep.target) &#123;</span><br><span class="line">        watcher.depend()</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> watcher.val</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *初始化 watch</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">vm</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">watch</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">initWatch</span>(<span class="params">vm, watch</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!watch || <span class="keyword">typeof</span> watch !== <span class="string">&#x27;object&#x27;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> watch) &#123;</span><br><span class="line">    <span class="keyword">const</span> handler = watch[key]</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(handler)) &#123;</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; handler.length; i++) &#123;</span><br><span class="line">        createWatcher(vm, key, handler[i])</span><br><span class="line">      &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      createWatcher(vm, key, handler)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">createWatcher</span> (<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">  vm,</span></span></span><br><span class="line"><span class="function"><span class="params">  expOrFn,</span></span></span><br><span class="line"><span class="function"><span class="params">  handler,</span></span></span><br><span class="line"><span class="function"><span class="params">  options</span></span></span><br><span class="line"><span class="function"><span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> handler === <span class="string">&#x27;object&#x27;</span>) &#123;</span><br><span class="line">    options = handler</span><br><span class="line">    handler = handler.handler</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> handler === <span class="string">&#x27;string&#x27;</span>) &#123;</span><br><span class="line">    handler = vm[handler]</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> vm.$watch(expOrFn, handler, options)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> uid = <span class="number">0</span>;</span><br><span class="line"><span class="comment">// 发布中心 存储订阅者 -发布订阅</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Dep</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 设置id,用于区分新Watcher和只改变属性值后新产生的Watcher</span></span><br><span class="line">    <span class="built_in">this</span>.id = uid++;</span><br><span class="line">    <span class="comment">// 储存订阅者的数组</span></span><br><span class="line">    <span class="built_in">this</span>.subs = [];</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 添加订阅者</span></span><br><span class="line">  <span class="function"><span class="title">addSub</span>(<span class="params">sub</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.subs.push(sub);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 监测是否已经存在sub中</span></span><br><span class="line">  <span class="function"><span class="title">depend</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (Dep.target) &#123;</span><br><span class="line">      Dep.target.addDep(<span class="built_in">this</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="title">notify</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 通知所有的订阅者(Watcher)</span></span><br><span class="line">    <span class="built_in">this</span>.subs.forEach(<span class="function"><span class="params">sub</span> =&gt;</span> sub.update());</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parsePath</span> (<span class="params">path</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!path) <span class="keyword">return</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> segments = path.split(<span class="string">&#x27;.&#x27;</span>)</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">obj</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; segments.length; i++) &#123;</span><br><span class="line">      <span class="keyword">if</span> (!obj) <span class="keyword">return</span></span><br><span class="line">      obj = obj[segments[i]]</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> obj</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 订阅者对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@class <span class="variable">Watcher</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Watcher</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">vm, expOrFn, cb, options, isRenderWatcher</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.depIds = &#123;&#125;; <span class="comment">// hash储存订阅者的id,避免重复的订阅者</span></span><br><span class="line">    <span class="built_in">this</span>.vm = vm; <span class="comment">// 被订阅的数据一定来自于当前Vue实例</span></span><br><span class="line">    <span class="keyword">if</span> (isRenderWatcher) &#123;</span><br><span class="line">      <span class="built_in">this</span>.vm._watcher = isRenderWatcher</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (options) &#123;</span><br><span class="line">      <span class="keyword">if</span> (options.user) &#123;</span><br><span class="line">        <span class="built_in">this</span>.user = options.user</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (options.lazy) &#123;</span><br><span class="line">        <span class="built_in">this</span>.lazy = options.lazy</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">this</span>.cb = cb</span><br><span class="line">    <span class="built_in">this</span>.dirty = <span class="built_in">this</span>.lazy</span><br><span class="line">    <span class="built_in">this</span>.deps = []</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> expOrFn === <span class="string">&#x27;function&#x27;</span>) &#123;</span><br><span class="line">      <span class="built_in">this</span>.getter = expOrFn; <span class="comment">// 当数据更新时想要做的事情</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.getter = parsePath(expOrFn)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">this</span>.val = <span class="built_in">this</span>.get(); <span class="comment">// 维护更新之前的数据</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 对外暴露的接口，用于在订阅的数据被更新时，由订阅者管理员(Dep)调用</span></span><br><span class="line">  <span class="function"><span class="title">update</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.run();</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">addDep</span>(<span class="params">dep</span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 如果在depIds的hash中没有当前的id,可以判断是新Watcher,因此可以添加到dep的数组中储存</span></span><br><span class="line">    <span class="comment">// 此判断是避免同id的Watcher被多次储存</span></span><br><span class="line">    <span class="keyword">if</span> (!<span class="built_in">this</span>.depIds.hasOwnProperty(dep.id)) &#123;</span><br><span class="line">      <span class="comment">//   console.log(this.depIds,dep.id);</span></span><br><span class="line">      <span class="built_in">this</span>.depIds[dep.id] = dep;</span><br><span class="line">      <span class="built_in">this</span>.deps.push(dep)</span><br><span class="line"></span><br><span class="line">      dep.addSub(<span class="built_in">this</span>);</span><br><span class="line">      <span class="built_in">console</span>.log(dep)</span><br><span class="line">    &#125;<span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">//   console.log(dep.id,&#x27;重复订阅&#x27;)</span></span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">run</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> val = <span class="built_in">this</span>.get();</span><br><span class="line">  </span><br><span class="line">    <span class="keyword">if</span> (val !== <span class="built_in">this</span>.val) &#123;</span><br><span class="line">      <span class="keyword">const</span> oldVal = <span class="built_in">this</span>.val</span><br><span class="line">      <span class="built_in">this</span>.val = val;</span><br><span class="line">      <span class="built_in">this</span>.cb.call(<span class="built_in">this</span>.vm, val, oldVal);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="function"><span class="title">get</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">    <span class="comment">// 当前订阅者(Watcher)读取被订阅数据的最新更新后的值时，通知订阅者管理员收集当前订阅者</span></span><br><span class="line">    pushTarget(<span class="built_in">this</span>)</span><br><span class="line">    <span class="keyword">const</span> vm = <span class="built_in">this</span>.vm</span><br><span class="line">    <span class="keyword">const</span> val = <span class="built_in">this</span>.getter.call(vm, vm)</span><br><span class="line">    <span class="comment">// 置空，用于下一个Watcher使用</span></span><br><span class="line">    popTarget()</span><br><span class="line">    <span class="keyword">return</span> val;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * 专门为 computed watch 设计的方法</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@memberof <span class="variable">Watcher</span></span></span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  evaluate () &#123;</span><br><span class="line">    <span class="built_in">this</span>.val = <span class="built_in">this</span>.get()</span><br><span class="line">    <span class="built_in">this</span>.dirty = <span class="literal">false</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * Depend on all deps collected by this watcher.</span></span><br><span class="line"><span class="comment">   * 收集所有的 watch</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  depend () &#123;</span><br><span class="line">    <span class="keyword">let</span> i = <span class="built_in">this</span>.deps.length</span><br><span class="line">    <span class="keyword">while</span> (i--) &#123;</span><br><span class="line">      <span class="built_in">this</span>.deps[i].depend()</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 为Dep类设置一个静态属性,默认为null,工作时指向当前的Watcher</span></span><br><span class="line">Dep.target = <span class="literal">null</span></span><br><span class="line"><span class="keyword">const</span> targetStack = []</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pushTarget</span> (<span class="params">target</span>) </span>&#123;</span><br><span class="line">  targetStack.push(target)</span><br><span class="line">  Dep.target = target</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">popTarget</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  targetStack.pop()</span><br><span class="line">  Dep.target = targetStack[targetStack.length - <span class="number">1</span>]</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 监听者,监听对象属性值的变化</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Observer</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="title">constructor</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">      <span class="comment">// 遍历属性值</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(value)) &#123;</span><br><span class="line"></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="built_in">this</span>.walk(value)</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="title">walk</span>(<span class="params">obj</span>)</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> keys = <span class="built_in">Object</span>.keys(obj);</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>;i&lt; keys.length; i++) &#123;</span><br><span class="line">      <span class="comment">// Object.defineProperty的处理逻辑</span></span><br><span class="line">      defineReactive(obj, keys[i], obj[keys[i]])</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">defineReactive</span>(<span class="params">obj, key, val</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> dep = <span class="keyword">new</span> Dep();</span><br><span class="line">  <span class="comment">// 给当前属性的值添加监听</span></span><br><span class="line">  <span class="built_in">Object</span>.defineProperty(obj, key, &#123;</span><br><span class="line">    enumerable: <span class="literal">true</span>,</span><br><span class="line">    configurable: <span class="literal">true</span>,</span><br><span class="line">    get: <span class="function">() =&gt;</span> &#123;</span><br><span class="line">      <span class="comment">// 如果Dep类存在target属性，将其添加到dep实例的subs数组中</span></span><br><span class="line">      <span class="comment">// target指向一个Watcher实例，每个Watcher都是一个订阅者</span></span><br><span class="line">      <span class="comment">// Watcher实例在实例化过程中，会读取data中的某个属性，从而触发当前get方法</span></span><br><span class="line">      <span class="keyword">if</span> (Dep.target) &#123;</span><br><span class="line">        dep.depend();</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> val;</span><br><span class="line">    &#125;,</span><br><span class="line">    set: <span class="function"><span class="params">newVal</span> =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">if</span> (val === newVal) <span class="keyword">return</span>;</span><br><span class="line">      val = newVal;</span><br><span class="line">      <span class="comment">// 对新值进行监听</span></span><br><span class="line">      <span class="comment">// 通知所有订阅者，数值被改变了</span></span><br><span class="line">      dep.notify();</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">observe</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 不考虑复杂类型  源码递归实现</span></span><br><span class="line">  <span class="keyword">if</span> (!value || <span class="keyword">typeof</span> value !== <span class="string">&#x27;object&#x27;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> Observer(value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> vm = <span class="keyword">new</span> Vue(&#123;</span><br><span class="line">  data: &#123;</span><br><span class="line">    hello: <span class="string">&#x27;hello world&#x27;</span>,</span><br><span class="line">    age:<span class="number">222</span>,</span><br><span class="line">    sex: <span class="string">&#x27;22&#x27;</span></span><br><span class="line">  &#125;,</span><br><span class="line">  template: <span class="string">`</span></span><br><span class="line"><span class="string">    &lt;!-- &lt;h1&gt; &#123;&#123;hello&#125;&#125;&lt;/h1&gt; --&gt;</span></span><br><span class="line"><span class="string">    &lt;h1&gt; &#123;&#123;showAge&#125;&#125;&lt;/h1&gt;</span></span><br><span class="line"><span class="string">    &lt;h1&gt; &#123;&#123;sex&#125;&#125;&lt;/h1&gt;</span></span><br><span class="line"><span class="string">    &lt;button id=&quot;change&quot;&gt;change&lt;/button&gt;</span></span><br><span class="line"><span class="string">  `</span>,</span><br><span class="line">  watch: &#123;</span><br><span class="line">    age: &#123;</span><br><span class="line">      handler: <span class="function"><span class="keyword">function</span> (<span class="params">newVal, oldVal</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(newVal, oldVal)</span><br><span class="line">      &#125;,</span><br><span class="line">      immediate: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  computed: &#123;</span><br><span class="line">    <span class="function"><span class="title">showAge</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="string">&#x27;年龄是&#x27;</span> + <span class="built_in">this</span>.age</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">vm.$mount(<span class="string">&#x27;#app&#x27;</span>)</span><br><span class="line"></span><br></pre></td></tr></table></figure>

</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">志非</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://fif.gitee.io/blog/2021/04/27/vue/vue-code-6.reactive/">https://fif.gitee.io/blog/2021/04/27/vue/vue-code-6.reactive/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://fif.gitee.io/blog" target="_blank">Jeffery Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/vue/">vue</a><a class="post-meta__tags" href="/blog/tags/vue-%E6%BA%90%E7%A0%81/">vue 源码</a></div><div class="post_share"><div class="social-share" data-image="https://gitee.com/FIF/pic-beg/raw/master/images/vue/mvvm.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/04/30/vue/vue-code-7-compiler/"><img class="prev-cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vuetemplate.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">（Vue源码五）Vue 编译原理</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/04/24/tools/gitlab/index/"><img class="next-cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/Hexo-logo.png" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Gitlab webhook 配置企业微信机器人</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2021/04/12/vue/vue-code-3.build/" title="（Vue源码一）Vue 源码设计和构建流程"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/Vue.js-i18n-768x512.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-12</div><div class="title">（Vue源码一）Vue 源码设计和构建流程</div></div></a></div><div><a href="/blog/2021/04/17/vue/vue-code-4.debugger/" title="（Vue源码二）Vue实例挂载流程"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/1_b2Ig4HR2UOQEV5I2QnQrrw.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-17</div><div class="title">（Vue源码二）Vue实例挂载流程</div></div></a></div><div><a href="/blog/2021/04/23/vue/vue-code-5.mergeOptions/" title="（Vue源码三）Vue 丰富的选项合并策略"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vue-highcharts_1200.webp" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-23</div><div class="title">（Vue源码三）Vue 丰富的选项合并策略</div></div></a></div><div><a href="/blog/2021/04/30/vue/vue-code-7-compiler/" title="（Vue源码五）Vue 编译原理"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vuetemplate.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-30</div><div class="title">（Vue源码五）Vue 编译原理</div></div></a></div><div><a href="/blog/2021/05/04/vue/vue-code-8.component/" title="（Vue源码六）Vue 组件原理分析"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-04</div><div class="title">（Vue源码六）Vue 组件原理分析</div></div></a></div><div><a href="/blog/2021/05/14/vue/vue-code-9.event/" title="（Vue源码七）Vue 事件"><img class="cover" src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-05-14</div><div class="title">（Vue源码七）Vue 事件</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src= "" data-lazy-src="/blog/img/home/avatar.jpeg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">志非</div><div class="author-info__description">自己变得更好，生活才会更美好</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">12</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">6</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">7</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/JefferyXZF"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/JefferyXZF" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="https://www.yuque.com/jeffery-kkrpn/uz24n9" target="_blank" title="语雀"><i class="fa fa-folder-open"></i></a><a class="social-icon" href="https://mail.qq.com/" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">越努力越幸运</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%9D%E8%80%83"><span class="toc-number">1.</span> <span class="toc-text">思考</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F%E5%8E%9F%E7%90%86%E6%B5%81%E7%A8%8B%E5%9B%BE%E5%88%86%E6%9E%90"><span class="toc-number">2.</span> <span class="toc-text">响应式原理流程图分析</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#vue-%E5%B8%B8%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="toc-number">3.</span> <span class="toc-text">vue 常用实例</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%93%8D%E5%BA%94%E5%BC%8F"><span class="toc-number">4.</span> <span class="toc-text">初始化响应式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#initProps-%E5%88%9D%E5%A7%8B%E5%8C%96props"><span class="toc-number">5.</span> <span class="toc-text">initProps - 初始化props</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#initMethods-%E5%88%9D%E5%A7%8B%E5%8C%96-methods"><span class="toc-number">6.</span> <span class="toc-text">initMethods - 初始化 methods</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#initData-%E5%88%9D%E5%A7%8B%E5%8C%96-data"><span class="toc-number">7.</span> <span class="toc-text">initData - 初始化 data</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#data-%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%86"><span class="toc-number">7.1.</span> <span class="toc-text">data 依赖收集</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#dep-%E5%AE%9E%E4%BE%8B%E5%8C%96"><span class="toc-number">7.2.</span> <span class="toc-text">dep 实例化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#data-%E6%B4%BE%E5%8F%91%E6%9B%B4%E6%96%B0"><span class="toc-number">7.3.</span> <span class="toc-text">data 派发更新</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BE%9D%E8%B5%96%E6%B8%85%E9%99%A4"><span class="toc-number">7.4.</span> <span class="toc-text">依赖清除</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#initComputed-%E5%88%9D%E5%A7%8B%E5%8C%96-compouted"><span class="toc-number">8.</span> <span class="toc-text">initComputed - 初始化 compouted</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#computed-%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%86"><span class="toc-number">8.1.</span> <span class="toc-text">computed 依赖收集</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#computed-%E6%B4%BE%E5%8F%91%E6%9B%B4%E6%96%B0"><span class="toc-number">8.2.</span> <span class="toc-text">computed 派发更新</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#initWatch-%E5%88%9D%E5%A7%8B%E5%8C%96-watch"><span class="toc-number">9.</span> <span class="toc-text">initWatch - 初始化 watch</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#watch-%E4%BE%9D%E8%B5%96%E6%94%B6%E9%9B%86"><span class="toc-number">9.1.</span> <span class="toc-text">watch 依赖收集</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#watch-%E6%B4%BE%E5%8F%91%E6%9B%B4%E6%96%B0"><span class="toc-number">9.2.</span> <span class="toc-text">watch 派发更新</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Watcher"><span class="toc-number">10.</span> <span class="toc-text">Watcher</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F-API"><span class="toc-number">11.</span> <span class="toc-text">响应式 API</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#set"><span class="toc-number">11.1.</span> <span class="toc-text">set</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#del"><span class="toc-number">11.2.</span> <span class="toc-text">del</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%93%8D%E5%BA%94%E5%BC%8F%E8%BF%87%E7%A8%8B"><span class="toc-number">12.</span> <span class="toc-text">响应式过程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%89%8B%E5%8A%A8%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E5%93%8D%E5%BA%94%E5%BC%8F"><span class="toc-number">13.</span> <span class="toc-text">手动实现一个响应式</span></a></li></ol></div></div><script defer="defer" data-pjax="data-pjax" src="/blog/js/card_clock.js"></script><div class="card-widget card-clock"><div id="clock"><img v-if="clockshow == &quot;false&quot;" alt="" src= "" data-lazy-src="/blog/img/weather/loading.gif" height="120px" width="100%"/><table class="clock" v-if="clockshow"><tbody><tr><td class="clockdate">{{date}}</td><td class="weatherimg"><img id="weatherimg" :src="weatherimg" alt=""/></td><td class="temperature">{{temperature}}</td><td class="humidityimg"><img id="humidityimg" :src="humidityimg" alt=""/></td><td class="humidity">{{humidity}}</td></tr><tr class="time"><td colspan="5">{{time}}</td></tr><tr><td class="usaqi" colspan="1"><span>{{ip}}</span></td><td class="city" colspan="2">{{city}}</td><td class="daylight" colspan="2">{{daylight}}</td></tr></tbody></table></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/05/24/tools/hexo/advanced/" title="Hexo 博客页面性能优化"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/Hexo-logo.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Hexo 博客页面性能优化"/></a><div class="content"><a class="title" href="/blog/2021/05/24/tools/hexo/advanced/" title="Hexo 博客页面性能优化">Hexo 博客页面性能优化</a><time datetime="2021-05-23T16:00:00.000Z" title="发表于 2021-05-24 00:00:00">2021-05-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/05/14/vue/vue-code-9.event/" title="（Vue源码七）Vue 事件"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码七）Vue 事件"/></a><div class="content"><a class="title" href="/blog/2021/05/14/vue/vue-code-9.event/" title="（Vue源码七）Vue 事件">（Vue源码七）Vue 事件</a><time datetime="2021-05-13T16:00:00.000Z" title="发表于 2021-05-14 00:00:00">2021-05-14</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/05/04/vue/vue-code-8.component/" title="（Vue源码六）Vue 组件原理分析"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/components.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码六）Vue 组件原理分析"/></a><div class="content"><a class="title" href="/blog/2021/05/04/vue/vue-code-8.component/" title="（Vue源码六）Vue 组件原理分析">（Vue源码六）Vue 组件原理分析</a><time datetime="2021-05-03T16:00:00.000Z" title="发表于 2021-05-04 00:00:00">2021-05-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/04/30/vue/vue-code-7-compiler/" title="（Vue源码五）Vue 编译原理"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/vuetemplate.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码五）Vue 编译原理"/></a><div class="content"><a class="title" href="/blog/2021/04/30/vue/vue-code-7-compiler/" title="（Vue源码五）Vue 编译原理">（Vue源码五）Vue 编译原理</a><time datetime="2021-04-29T16:00:00.000Z" title="发表于 2021-04-30 00:00:00">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/04/27/vue/vue-code-6.reactive/" title="（Vue源码四）数据响应式原理"><img src= "" data-lazy-src="https://gitee.com/FIF/pic-beg/raw/master/images/vue/mvvm.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="（Vue源码四）数据响应式原理"/></a><div class="content"><a class="title" href="/blog/2021/04/27/vue/vue-code-6.reactive/" title="（Vue源码四）数据响应式原理">（Vue源码四）数据响应式原理</a><time datetime="2021-04-26T16:00:00.000Z" title="发表于 2021-04-27 00:00:00">2021-04-27</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2021 By 志非</div><div class="footer_custom_text">Hi, welcome to my <a href="/">blog</a>!</div><div id="workboard"></div><script async="async" src="/blog/js/runtime.js"></script></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="https://cdn.jsdelivr.net/npm/vue"></script><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'JC72d1A7XBwC26rGCKMVn5CS-MdYXbMMI',
      appKey: 'xI6bG7FseICz8ShKdmWVe7N1',
      placeholder: 'Please leave your footprints',
      avatar: 'https://gitee.com/FIF/pic-beg/raw/master/images/vue/1619248532079-avatar_coment.webp',
      meta: 'nick,mail,link'.split(','),
      pageSize: '10',
      lang: 'zh-CN',
      recordIP: false,
      serverURLs: '',
      emojiCDN: '',
      emojiMaps: "",
      enableQQ: true,
      path: window.location.pathname,
      requiredFields: ["nick,mail"],
      visitor: false,
      avatar_cdn: 'https://www.gravatar.com/avatar/'
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="false" pjax="true" muted></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>